(function(window, undefined) {
	let that, body;
	let bodySet = [];

	function Snack(map, food, option) {
		option = option || {};
		this.width = option.width || 20;
		this.height = option.height || 20;
		this.map = map;
		this.body = [
			{x: 3, y: 3, background: 'red'},
			{x: 2, y: 3, background: 'green'},
			{x: 1, y: 3, background: 'green'},
		];
		this.rear;
		this.decration = 'right';

		that = this;
		body = this.body;
	}

	Snack.prototype = {
		constructor: Snack,
		render: function() {
			remove();
			for (let i = 0, len = body.length; i < len; i++) {
				let div = document.createElement('div');
				div.style.width = this.width + 'px';
				div.style.height = this.height + 'px';
				div.style.left = body[i].x * this.width + 'px';
				div.style.top = body[i].y * this.height + 'px';
				div.style.background = body[i].background;
				div.style.border = '1px solid #ccc';
				div.style.position = 'absolute';
				this.map.appendChild(div);
				bodySet.push(div);
			}
		},
		move: function() {
			let len = body.length - 1;
			this.rear = {x: body[len].x, y: body[len].y};
			// 1. 先渲染身体
			for (let i = len ; i >= 1; i--) {
				body[i].x = body[i - 1].x;
				body[i].y = body[i - 1].y;
			}
			// 2. 根据方向渲染头部
			switch(this.decration) {
				case 'up': 
					body[0].y--;
					break;
				case 'down':
					body[0].y++; 
					break;
				case 'left':
					body[0].x--; 
					break;
				case 'right':
					body[0].x++; 
					break;
			}
			this.eatFood();
			this.render();
		},
		eatFood: function() {
			if(this.body[0].x == food.x && this.body[0].y == food.y) {
				let newBody = {
					x: that.rear.x,
					y: that.rear.y,
					background: 'green'
				};
				body.push(newBody);
				food.randomXy();
				food.render();
			}
		}
	}

	// 清除以前的创建的div，即清除移动痕迹
	function remove() {
		if (bodySet.length) {
			for (let i = 0, len = body.length; i < len; i++) {
				if (bodySet[0]) {
					this.map.removeChild(bodySet[0]);
					bodySet.shift();
				}
			}
		} else {
			return;
		}
	}

	window.Snack = Snack;
})(window, undefined);
